package com.tutu.user.security;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

/**
 * 
 *  @author tutu
 *	@date 2013-11-19
 *	@company cjcc
 *	@version ssi_1.0 1.0
 */
@Service("myAccessDecisionManager")
public class MyAccessDecisionManager implements AccessDecisionManager{

	/** 
     * @description 认证用户是否具有权限访问该url地址 
     */
	@Override
	public void decide(Authentication authentication, Object obj,
			Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
	        if(configAttributes==null) return;
	        for(Iterator<ConfigAttribute> configAttributeIterator = configAttributes.iterator(); configAttributeIterator.hasNext(); ){
	            ConfigAttribute configAttribute = configAttributeIterator.next();
	            String needRole = configAttribute.getAttribute();
	            //authentication.getAuthorities()  用户所有的权限  
	            for(GrantedAuthority grantedAuthority : authentication.getAuthorities()){  
	                if(needRole.equals(grantedAuthority.getAuthority())){
	                    return;  
	                }  
	            }
	        }
	        throw new AccessDeniedException("用户无此权限");  
	}

	/** 
     * 启动时候被AbstractSecurityInterceptor调用，决定AccessDecisionManager是否可以执行传递ConfigAttribute。 
     */  
	@Override
	public boolean supports(ConfigAttribute configattribute) {
		return Boolean.TRUE;
	}

	/** 
     * 被安全拦截器实现调用，包含安全拦截器将显示的AccessDecisionManager支持安全对象的类型 
     */
	@Override
	public boolean supports(Class<?> clazz) {
		return Boolean.TRUE;
	}

}
